<template>
    <div class="report-container">
        <div class="upload-section">
            <el-card class="report-card" shadow="hover">
                <div class="upload-content" @click="handleItemInfo">
                    <div class="icon-wrapper">
                        <el-icon class="card-icon">
                            <Upload />
                        </el-icon>
                    </div>
                    <div class="text-content">
                        <h3>上传体检报告</h3>
                        <p class="card-desc">仅支持图片和PDF格式文件</p>
                    </div>
                </div>
            </el-card>
        </div>

        <div class="manual-section">
            <el-card class="report-card" shadow="hover">
                <div class="manual-content" @click="showManualDialog = true">
                    <div class="icon-wrapper">
                        <el-icon class="card-icon">
                            <EditPen />
                        </el-icon>
                    </div>
                    <div class="text-content">
                        <h3>手动输入体检模版</h3>
                        <p class="card-desc">按模版格式录入体检数据</p>
                    </div>
                </div>
            </el-card>
        </div>

        <el-dialog v-model="showUploadDialog" title="上传体检报告" width="60%" :before-close="handleClose">
            <div class="upload-dialog-content">
                <div class="template-hint">
                    <el-button link type="warning" @click="showTemplate = true" class="template-btn">
                        <el-icon>
                            <QuestionFilled />
                        </el-icon>
                        暂未知道模版？点击查看模版
                    </el-button>
                </div>

                <div v-loading="isAnalyzing" element-loading-text="正在分析体检数据..."
                    element-loading-background="rgba(255, 255, 255, 0.9)">
                    <el-upload class="upload-area" drag action="/api/common/upload" :on-success="handleUploadSuccess"
                        :on-error="handleUploadError" :before-upload="beforeUpload" :file-list="uploadedFiles"
                        :limit="1" :on-exceed="handleExceed" :on-remove="handleRemove" :headers="uploadHeaders">
                        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                        <div class="el-upload__text">
                            将文件拖到此处，或<em>点击上传</em>
                        </div>
                        <template #tip>
                            <div class="el-upload__tip">
                                支持jpg、png、pdf格式文件
                            </div>
                        </template>
                    </el-upload>

                    <div v-if="uploadedFiles.length" class="preview-area">
                        <h4>已上传文件</h4>
                        <div class="file-list">
                            <div v-for="file in uploadedFiles" :key="file.url" class="file-item">
                                <img v-if="isImage(file.name)" :src="file.url" class="preview-image">
                                <div v-else-if="isPDF(file.name)" class="pdf-preview">
                                    <el-icon>
                                        <Document />
                                    </el-icon>
                                    <span>{{ file.name }}</span>
                                </div>
                                <el-icon class="delete-icon" @click="removeFile(file)">
                                    <Delete />
                                </el-icon>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleClose">取消</el-button>
                    <el-button type="primary" @click="analyzeReport" :loading="isAnalyzing"
                        :disabled="!uploadedFiles.length || isAnalyzing">
                        {{ isAnalyzing ? '正在分析...' : '分析体检数据' }}
                    </el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 手动输入对话框 -->
        <el-dialog v-model="showManualDialog" title="手动输入体检数据" width="80%" :before-close="handleManualClose"
            class="manual-dialog">
            <div class="type-container">
                <div class="type-grid">
                    <el-card v-for="type in physicalTypes" :key="type.id" class="type-card" shadow="hover"
                        @click="handleTypeClick(type)">
                        <div class="type-content">
                            <span class="type-name">{{ type.physicalName }}</span>
                        </div>
                    </el-card>
                </div>
            </div>

            <template #footer>
                <div class="manual-dialog-footer">
                    <el-button @click="handleManualClose">取消</el-button>
                    <div class="footer-right">
                        <el-button type="primary" @click="handlePreview">
                            整体预览
                        </el-button>
                    </div>
                </div>
            </template>
        </el-dialog>

        <!-- 体检项目输入对话框 -->
        <el-dialog v-model="showItemDialog" :title="currentType?.physicalName" width="60%" class="item-dialog">
            <div class="items-form">
                <el-form label-width="120px">
                    <el-form-item v-for="item in physicalItems" :key="item.id" :label="item.physicalItemName">
                        <el-input v-model="getBindingValue(item).content" :placeholder="`请输入${item.physicalItemName}`"
                            type="number" :precision="2" :step="0.01" @input="handleInput($event, item)"
                            @blur="handleBlur($event, item)">
                            <template #append>{{ item.unit }}</template>
                        </el-input>
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <div class="item-dialog-footer">
                    <div class="footer-left">
                        <el-button @click="resetItemValues">重置</el-button>
                    </div>
                    <div class="footer-right">
                        <el-button @click="showItemDialog = false">取消</el-button>
                        <el-button type="primary" @click="saveItemValues">
                            继续
                        </el-button>
                    </div>
                </div>
            </template>
        </el-dialog>
        <!-- 添加模版预览对话框 -->
        <el-dialog v-model="showTemplate" title="体检报告模版" width="50%" class="template-dialog">
            <div class="template-preview">
                <img src="@/assets/TemplateReport.png" alt="体检报告模版" class="template-image">
            </div>
        </el-dialog>

        <!-- 修改整体预览对话框 -->
        <el-dialog v-model="showPreview" title="体检数据预览" width="80%" class="preview-dialog">
            <div class="preview-content">
                <el-collapse v-model="activeCollapse">
                    <el-collapse-item v-for="type in physicalTypes" :key="type.id" :name="type.id">
                        <template #title>
                            <div class="collapse-header">
                                <div class="header-left">
                                    <el-icon class="type-icon">
                                        <DataLine />
                                    </el-icon>
                                    <span class="type-title">{{ type.physicalName }}</span>
                                </div>
                                <div class="header-right">
                                    <el-progress :percentage="getCompletionRate(type.id)"
                                        :status="getProgressStatus(type.id)" class="completion-progress" />
                                </div>
                            </div>
                        </template>

                        <div class="preview-items">
                            <div v-for="item in getItemsByType(type.id)" :key="item.id" class="preview-item">
                                <div class="item-info">
                                    <span class="item-name">{{ item.physicalItemName }}</span>
                                </div>
                                <el-input v-model="getBindingValue(item).content"
                                    :placeholder="`请输入${item.physicalItemName}的值`" type="number" :precision="2"
                                    :step="0.01" @input="handleInput($event, item)" @blur="handleBlur($event, item)"
                                    class="preview-input">
                                    <template #append>{{ item.unit }}</template>
                                </el-input>
                            </div>
                        </div>
                    </el-collapse-item>
                </el-collapse>
            </div>

            <template #footer>
                <div class="preview-footer">
                    <div class="footer-left">
                        <div class="completion-info">
                            <span>总体完成度</span>
                            <el-progress :percentage="getTotalCompletionRate()" :format="format => `${format}%`"
                                class="total-progress" />
                        </div>
                    </div>
                    <div class="footer-right">
                        <el-button @click="resetAllValues">重置全部</el-button>
                        <el-button type="primary" @click="generatePhysicalReport">生成您的体检模版</el-button>
                    </div>
                </div>
            </template>
        </el-dialog>

        <!-- 在最后一个对话框后添加体检报告预览对话框 -->
        <el-dialog v-model="showReport" title="体检报告预览" width="50%" class="report-dialog" :close-on-click-modal="false">
            <div v-if="isGenerating" class="generating-content">
                <div class="generating-animation">
                    <el-icon class="rotating">
                        <Loading />
                    </el-icon>
                </div>
                <h3>正在生成您的体检报告</h3>
                <p class="generating-tip">请稍候，这可能需要一点时间...</p>
            </div>

            <div v-else class="report-preview">
                <img :src="reportUrl" alt="体检报告" class="report-image">
            </div>

            <template #footer>
                <div class="report-footer">
                    <el-button @click="handleReportCancel">返回</el-button>
                    <div class="action-buttons">
                        <el-button @click="handleSaveReport" :loading="isSaving">
                            保存
                        </el-button>
                        <el-button type="primary" @click="handleSaveAndDownload" :loading="isAccepting">
                            保存并下载
                        </el-button>
                    </div>
                </div>
            </template>
        </el-dialog>
        <!-- 在合适的位置添加识别结果对话框 -->
        <el-dialog v-model="showResultDialog" title="体检报告识别结果" width="50%" :close-on-click-modal="false">
            <div class="recognition-results">
                <el-alert type="info" :closable="false" class="result-tip">
                    <template #default>
                        <p class="tip-text">具体修改请保存后到用户信息更改！</p>
                        <el-button type="text" @click="goToHealthStatus" class="goto-btn">
                            前往健康状态 <el-icon>
                                <ArrowRight />
                            </el-icon>
                        </el-button>
                    </template>
                </el-alert>

                <el-table :data="recognitionResults" border class="result-table">
                    <el-table-column prop="itemName" label="检测项目" width="180" />
                    <el-table-column label="检测结果">
                        <template #default="scope">
                            {{ scope.row.content }} {{ scope.row.unit }}
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showResultDialog = false">取消</el-button>
                    <el-button type="primary" @click="handleSaveResults" :loading="isSavingResults">
                        保存
                    </el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 在合适的位置添加按钮 -->
        <el-button type="primary" @click="showReportRecords" class="view-records-btn">
            <el-icon><Document /></el-icon>
            查看上传记录
        </el-button>

        <!-- 添加记录查看对话框 -->
        <el-dialog
            v-model="showRecordsDialog"
            title="体检报告记录"
            width="70%"
            class="records-dialog"
        >
            <el-table 
                :data="reportRecords" 
                style="width: 100%"
                height="400"
                :max-height="400"
            >
                <el-table-column prop="userName" label="用户名" width="120" fixed />
                
                <el-table-column label="文件路径" min-width="200">
                    <template #default="scope">
                        <el-button 
                            link 
                            type="primary" 
                            @click="previewPdf(scope.row.filePath)"
                        >
                            {{ getShortPath(scope.row.filePath) }}
                        </el-button>
                    </template>
                </el-table-column>
                
                <el-table-column label="提交时间" width="180">
                    <template #default="scope">
                        {{ formatDate(scope.row.uploadDate) }}
                    </template>
                </el-table-column>
                
                <el-table-column label="状态" width="100">
                    <template #default="scope">
                        <el-tag :type="scope.row.status === 1 ? 'success' : 'warning'">
                            {{ scope.row.status === 1 ? '已通过' : '未通过' }}
                        </el-tag>
                    </template>
                </el-table-column>
                
                <el-table-column label="操作" width="100" fixed="right">
                    <template #default="scope">
                        <el-button
                            type="primary"
                            link
                            @click="downloadPdf(scope.row.filePath)"
                        >
                            <el-icon><Download /></el-icon>
                            下载
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Upload, UploadFilled, Document, Delete, EditPen, DataLine, Loading, ArrowRight, Download } from '@element-plus/icons-vue'
import { useTokenStore } from '@/stores/token'
import { PhysicalTypeService, PhysicalItemByTypeService, PhysicalItems, GeneratePhysicalReportService, SavePhysicalReportService, CancelPhysicalService, OcrAwardHandleService } from '@/api/physical'
import { useRouter } from 'vue-router'
import { ArrowRight as ArrowRightIcon } from '@element-plus/icons-vue'
import { UserReportService } from '@/api/user'

const showUploadDialog = ref(false)
const uploadedFiles = ref([])
const originalFile = ref(null)
const handleItemInfo = async () => {
    const result = await PhysicalItems()
    if (result.code === 200) {
        result.data.forEach(item => {
            const field = getItemField(item.physicalItemName)
            if (field) {
                PhysicalItemDto.value[field].id = item.id
                PhysicalItemDto.value[field].typeId = item.typeId
                PhysicalItemDto.value[field].unit = item.unit
            }
        })
        showUploadDialog.value = true
    }
}
const tokenStore = useTokenStore()
const uploadHeaders =
{
    Authorization: tokenStore.getToken()
}

const beforeUpload = (file) => {
    const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf']
    if (!allowedTypes.includes(file.type)) {
        ElMessage.error('只支持 JPG、PNG 和 PDF 格式文件！')
        return false
    }
    const maxSize = 10 * 1024 * 1024 // 10MB
    if (file.size > maxSize) {
        ElMessage.error('文件大小不能超过10MB！')
        return false
    }
    return true
}

const handleUploadSuccess = (response, file) => {
    if (response.code === 200) {
        uploadedFiles.value = [{
            name: file.name,
            url: response.data.url,
            type: file.type
        }]
        originalFile.value = file.raw
        console.log('Upload success:', file)
        ElMessage.success('上传成功')
    } else {
        ElMessage.error(response.msg || '上传失败')
    }
}

const handleUploadError = () => {
    ElMessage.error('上传失败，请重试')
}

const handleExceed = () => {
    ElMessage.warning('只能上传一个文件，新文件将替换旧文件')
}

const isImage = (fileName) => {
    return /\.(jpg|jpeg|png)$/i.test(fileName)
}

const isPDF = (fileName) => {
    return /\.pdf$/i.test(fileName)
}

const removeFile = () => {
    uploadedFiles.value = []
    originalFile.value = null
}

const handleClose = () => {
    showUploadDialog.value = false
    uploadedFiles.value = []
    originalFile.value = null
}

// 添加新的响应式变量
const isAnalyzing = ref(false)

const router = useRouter()
const recognitionResults = ref([])
const showResultDialog = ref(false)


// 修改 analyzeReport 函数
const analyzeReport = async () => {
    if (!uploadedFiles.value.length || !originalFile.value) {
        ElMessage.warning('请先上传文件')
        return
    }

    try {
        isAnalyzing.value = true // 开始分析时显示加载动画

        // 创建 FormData 对象
        const formData = new FormData()
        formData.append('file', originalFile.value)
        formData.append('filePath', uploadedFiles.value[0].url)
        // 设置请求头
        const headers = {
            'Content-Type': 'multipart/form-data',
            ...uploadHeaders
        }

        // 调用OCR服务
        const result = await OcrAwardHandleService(formData, headers)

        if (result.code === 200) {
            console.log(result.data);
            recognitionResults.value = result.data
            showResultDialog.value = true
        } else {
            throw new Error(result.msg || '分析失败')
        }
    } catch (error) {
        ElMessage.error(error.message || '体检数据分析失败')
    } finally {
        isAnalyzing.value = false // 结束分析时隐藏加载动画
        handleClose()
    }
}

const isSavingResults = ref(false)
//保存数据
const handleSaveResults = async () => {
    try {
        isSavingResults.value = true
        recognitionResults.value.forEach(item => {
            const field = getItemField(item.itemName)
            if (field) {
                PhysicalItemDto.value[field].content = item.content
            }
        })

        // 保存体检数据
        const result1 = await SavePhysicalReportService(PhysicalItemDto.value)
        if (result1.code === 200) {
            ElMessage.success('保存成功')
            showUploadDialog.value = false
            showResultDialog.value = false
        } else {
            throw new Error(result1.msg || '体检数据保存失败')
        }
    }
    catch (error) {
        ElMessage.error(error.message || '体检数据保存失败')
    }
    finally {
        isSavingResults.value = false
    }
}
const showManualDialog = ref(false)
const showItemDialog = ref(false)
const showPreview = ref(false)
const physicalTypes = ref([])
const physicalItems = ref([])
const currentType = ref(null)
const itemValues = ref({})
const PhysicalItemDto = ref({
    systolicPressure://收缩压
    {
        id: null,
        typeId: null,
        content: null,
        physicalItemName: "收缩压",
        name: "systolicPressure",
        unit: null
    },
    diastolicPressure: //舒张压
    {
        id: null,
        typeId: null,
        content: null,
        physicalItemName: "舒张压",
        name: "diastolicPressure",
        unit: null

    },
    whiteBloodCell://白细胞
    {
        id: null,
        typeId: null,
        content: null,
        physicalItemName: "白细胞",
        name: "whiteBloodCell",
        unit: null

    },
    redBloodCell://红细胞
    {
        id: null,
        typeId: null,
        content: null,
        physicalItemName: "红细胞",
        name: "redBloodCell",
        unit: null

    },
    hemoglobin://血红蛋白
    {
        id: null,
        typeId: null,
        content: null,
        physicalItemName: "血红蛋白",
        name: "hemoglobin",
        unit: null

    },
    platelet://血小板
    {
        id: null,
        typeId: null,
        content: null,
        physicalItemName: "血小板",
        name: "platelet",
        unit: null

    },
    glucose://葡萄糖
    {
        id: null,
        typeId: null,
        content: null,
        physicalItemName: "葡萄糖",
        name: "glucose",
        unit: null

    },
    protein://蛋白质
    {
        id: null,
        typeId: null,
        content: null,
        physicalItemName: "蛋白质",
        name: "protein",
        unit: null

    },
    ketone://酮体
    {
        id: null,
        typeId: null,
        content: null,
        physicalItemName: "酮体",
        name: "ketone",
        unit: null

    },
    alt://谷丙转氨酶
    {
        id: null,
        typeId: null,
        content: null,
        physicalItemName: "谷丙转氨酶",
        name: "alt",
        unit: null

    },
    totalBil://总胆红素
    {
        id: null,
        typeId: null,
        content: null,
        physicalItemName: "总胆红素",
        name: "tBil",
        unit: null

    },
    alb://白蛋白
    {
        id: null,
        typeId: null,
        content: null,
        physicalItemName: "白蛋白",
        name: "alb",
        unit: null

    },
    bloodSugar://血糖
    {
        id: null,
        typeId: null,
        content: null,
        physicalItemName: "血糖",
        name: "bloodSugar",
        unit: null

    },
    totalCholesterol://总胆固醇
    {
        id: null,
        typeId: null,
        content: null,
        physicalItemName: "总胆固醇",
        name: "tCholesterol",
        unit: null

    },
    triglyceride://甘油三脂
    {
        id: null,
        typeId: null,
        content: null,
        physicalItemName: "甘油三脂",
        name: "triglyceride",
        unit: null

    },
    sinusRhythm: //窦性心率
    {
        id: null,
        typeId: null,
        content: null,
        physicalItemName: "窦性心率",
        name: "sinusRhythm",
        unit: null

    },
    creatinine://肌酐
    {
        id: null,
        typeId: null,
        content: null,
        physicalItemName: "肌酐",
        name: "creatinine",
        unit: null

    },
    urea://尿素
    {
        id: null,
        typeId: null,
        content: null,
        physicalItemName: "尿素",
        name: "urea",
        unit: null

    }
})

// 获取体检类型
const getPhysicalTypes = async () => {
    try {
        const result = await PhysicalTypeService()
        if (result.code === 200) {
            physicalTypes.value = result.data
        }
    } catch (error) {
        ElMessage.error('获取体检类型失败')
    }
}

// 点击体检类型卡片
const handleTypeClick = async (type) => {
    currentType.value = type
    try {
        const result = await PhysicalItemByTypeService(type.id)
        if (result.code === 200) {
            physicalItems.value = result.data
            // 设置对应项目的 id
            result.data.forEach(item => {
                const field = getItemField(item.physicalItemName)
                if (field) {
                    PhysicalItemDto.value[field].id = item.id
                }
            })
            showItemDialog.value = true

        }
    } catch (error) {
        ElMessage.error('获取体检项目失败')
    }
}

// 保存项目值
const saveItemValues = () => {
    showItemDialog.value = false
    ElMessage.success('保存成功')

}

// 根据类型获取项目
const getItemsByType = (typeId) => {
    const items = Object.entries(PhysicalItemDto.value)
        .filter(([_, value]) => value.typeId === typeId)
        .reduce((acc, [key, value]) => {
            acc[key] = value;
            return acc;
        }, {});

    return items
}

const handlePreview = async () => {
    try {
        const result = await PhysicalItems()
        if (result.code === 200) {
            result.data.forEach(item => {
                const field = getItemField(item.physicalItemName)
                if (field) {
                    PhysicalItemDto.value[field].id = item.id
                    PhysicalItemDto.value[field].typeId = item.typeId
                    PhysicalItemDto.value[field].unit = item.unit
                }
            })
        }
        showPreview.value = true
    }
    catch (error) {
        ElMessage.error('获取体检项目失败')
    }
}
// 关闭手动输入对话框
const handleManualClose = () => {
    showManualDialog.value = false
    itemValues.value = {}
}

// 监听手动输入对话框打开
watch(showManualDialog, async (newVal) => {
    if (newVal) {
        await getPhysicalTypes()
    }
})

const handleRemove = () => {
    uploadedFiles.value = []
}

// 根据项目名称获取对应 DTO 字段
const getItemField = (itemName) => {
    const fieldMap = {
        '收缩压': 'systolicPressure',
        '舒张压': 'diastolicPressure',
        '白细胞': 'whiteBloodCell',
        '红细胞': 'redBloodCell',
        '血红蛋白': 'hemoglobin',
        '血小板': 'platelet',
        '葡萄糖': 'glucose',
        '蛋白质': 'protein',
        '酮体': 'ketone',
        '谷丙转氨酶': 'alt',
        '总胆红素': 'totalBil',
        '白蛋白': 'alb',
        '血糖': 'bloodSugar',
        '总胆固醇': 'totalCholesterol',
        '甘油三脂': 'triglyceride',
        '窦性心率': 'sinusRhythm',
        '肌酐': 'creatinine',
        '尿素': 'urea'
    }
    return fieldMap[itemName]
}


// 获取绑定值
const getBindingValue = (item) => {
    const field = getItemField(item.physicalItemName)
    if (field) {
        // 如还没有置 id，则设置它
        if (!PhysicalItemDto.value[field].id) {
            PhysicalItemDto.value[field].id = item.id
        }
        return PhysicalItemDto.value[field]
    }
    return { content: '' }
}

// 添加重置函数
const resetItemValues = () => {
    // 重置当前类型相关的所有值
    physicalItems.value.forEach(item => {
        const field = getItemField(item.physicalItemName)
        if (field && PhysicalItemDto.value[field]) {
            // 只重置内容，保留id
            PhysicalItemDto.value[field].content = null
        }
    })
    ElMessage.success('已重置当前项目的输入值')
}
// 添加输入处理函数
const handleInput = (value, item) => {
    const field = getItemField(item.physicalItemName)
    if (field) {
        if (value === '') {
            PhysicalItemDto.value[field].content = null
            return
        }

        // 只允许输入数字和小数点
        const numValue = value.replace(/[^\d.]/g, '')
        PhysicalItemDto.value[field].content = numValue
    }
}

// 添加失去焦点处理函数
const handleBlur = (event, item) => {
    const field = getItemField(item.physicalItemName)
    if (field && PhysicalItemDto.value[field].content) {
        const value = PhysicalItemDto.value[field].content
        // 转换为数字并保留2位小数
        const num = parseFloat(value)
        if (!isNaN(num)) {
            PhysicalItemDto.value[field].content = num.toFixed(2)
        }
    }
}

// 加折叠面板的激活项
const activeCollapse = ref([]) // 默认全部展开
// 监听对话框打开，设置全部展开
watch(showPreview, (newVal) => {
    if (newVal) {
        // 设置所有类型ID为激活状态
        activeCollapse.value = physicalTypes.value.map(type => type.id)
    }
})

// 添加获取完成率的函数
const getCompletionRate = (typeId) => {
    const items = Object.values(PhysicalItemDto.value)
        .filter(item => item.typeId === typeId);

    if (items.length === 0) return 0;

    const filledCount = items.filter(item =>
        item.content !== null && item.content !== ''
    ).length;

    return Math.round((filledCount / items.length) * 100);
}

// 获取进度条状态
const getProgressStatus = (typeId) => {
    const rate = getCompletionRate(typeId);
    if (rate === 100) return 'success';
    if (rate > 0) return 'warning';
    return '';
}

// 获取总体完成率
const getTotalCompletionRate = () => {
    const allItems = Object.values(PhysicalItemDto.value);
    const filledCount = allItems.filter(item =>
        item.content !== null && item.content !== ''
    ).length;

    return Math.round((filledCount / allItems.length) * 100);
}

// 修改重置所有值的函数
const resetAllValues = () => {
    ElMessageBox.confirm(
        '确定要重置所有已输入的数据吗？此操作不可恢复。',
        '重置确认',
        {
            confirmButtonText: '确定重置',
            cancelButtonText: '取消',
            type: 'warning',
            confirmButtonClass: 'el-button--danger',
            center: true,
            draggable: true
        }
    )
        .then(() => {
            // 用户确认重置
            Object.values(PhysicalItemDto.value).forEach(item => {
                item.content = null;
            });
            ElMessage({
                type: 'success',
                message: '已重置所有数据',
                duration: 2000
            });
        })
        .catch(() => {
            // 用户取消重置
            ElMessage({
                type: 'info',
                message: '已取消重置',
                duration: 2000
            });
        });
};
const showReport = ref(false)
const reportUrl = ref('')
const PdfUrl = ref('')

// 添加新的响应式变量
const isGenerating = ref(false)
const isAccepting = ref(false)
const isSaving = ref(false)

// 修改生成报告函数
const generatePhysicalReport = async () => {
    try {
        showReport.value = true
        isGenerating.value = true

        const result = await GeneratePhysicalReportService(PhysicalItemDto.value)
        if (result.code == 200) {
            ElMessage.success('体检报告生成成功')
            reportUrl.value = result.data.imageUrl
            PdfUrl.value = result.data.pdfUrl
            isGenerating.value = false
        } else {
            throw new Error(result.msg)
        }
    } catch (error) {
        ElMessage.error(error.message || '生成体检报告失败')
        showReport.value = false
        isGenerating.value = false
    }
}

// 修改取处理函数
const handleReportCancel = async () => {
    try {
        await CancelPhysicalService()
        showReport.value = false
        showPreview.value = false
        reportUrl.value = ''
        PdfUrl.value = ''
    } catch (error) {
        ElMessage.error('操作失败')
    }
}

// 添加保存处理函数
const handleSaveReport = async () => {
    try {
        isSaving.value = true
        const result = await SavePhysicalReportService(PhysicalItemDto.value)
        if (result.code === 200) {
            ElMessage.success('报告保存成功')
            showReport.value = false
            showPreview.value = false
        } else {
            throw new Error(result.msg)
        }
    } catch (error) {
        ElMessage.error(error.message || '保存失败')
    } finally {
        isSaving.value = false
    }
}

// 修改保存并下载处理函数
const handleSaveAndDownload = async () => {
    try {
        isAccepting.value = true
        // 先保存
        const result = await SavePhysicalReportService(PhysicalItemDto.value)
        if (result.code === 200) {
            // 创建一个隐的 a 标签来下载
            const link = document.createElement('a')
            link.href = PdfUrl.value
            link.setAttribute('download', '体检报告.pdf') // 设置下载文件名
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)

            ElMessage.success('报告已保存并开始下载')
            showReport.value = false
            showPreview.value = false
        } else {
            throw new Error(result.msg)
        }
    } catch (error) {
        ElMessage.error(error.message || '操作失败')
    } finally {
        isAccepting.value = false
    }
}
//前往健康状态
const goToHealthStatus = () => {
    router.push('/user/health')
}

// 在 script setup 中添加新的响应式变量
const showTemplate = ref(false)  // 控制模板预览对话框的显示

// 添加新的响应式变量
const showRecordsDialog = ref(false)
const reportRecords = ref([])

// 获取报告记录
const showReportRecords = async () => {
    try {
        const result = await UserReportService()
        if (result.code === 200) {
            reportRecords.value = result.data
            showRecordsDialog.value = true
        } else {
            ElMessage.error('获取记录失败')
        }
    } catch (error) {
        console.error('获取记录失败:', error)
        ElMessage.error('获取记录失败')
    }
}

// 格式化日期
const formatDate = (dateString) => {
    if (!dateString) return '--'
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    })
}

// 获取短路径显示
const getShortPath = (path) => {
    if (!path) return '--'
    
    // 从路径中提取日期信息
    const dateMatch = path.match(/\/hsa\/(\d{4})\/(\d{2})\/(\d{2})\//)
    if (dateMatch) {
        const [_, year, month, day] = dateMatch
        // 格式化日期
        const formattedDate = `${year}年${month}月${day}日`
        return `${formattedDate}膳养智选体检报告`
    }
    
    return path
}

// 预览PDF
const previewPdf = (path) => {
    if (!path) return
    window.open(path, '_blank')
}

// 下载PDF
const downloadPdf = (path) => {
    if (!path) return
    const link = document.createElement('a')
    link.href = path
    link.setAttribute('download', `体检报告_${new Date().getTime()}.pdf`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
}
</script>

<style scoped>
.report-container {
    height: 100%;
    width: 100%;
    padding: 0;
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 0;
}

.upload-section,
.manual-section {
    width: 100%;
    height: 100%;
    padding: 30px;
}

.report-card {
    height: 100%;
    cursor: pointer;
    transition: all 0.3s;
    border-radius: 8px;
    overflow: hidden;
}

.report-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.upload-content,
.manual-content {
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
    padding: 60px 20px;
}

.icon-wrapper {
    flex: 1;
    display: flex;
    align-items: flex-start;
    justify-content: center;
    width: 100%;
    padding-top: 40px;
}

.text-content {
    text-align: center;
    flex: 2;
    display: flex;
    flex-direction: column;
    justify-content: center;
    gap: 16px;
}

.card-icon {
    font-size: 80px;
    color: #409EFF;
}

.manual-section .card-icon {
    color: #67C23A;
}

.text-content h3 {
    font-size: 28px;
    margin: 0;
    color: #303133;
    font-weight: 600;
}

.card-desc {
    font-size: 16px;
    color: #909399;
    margin: 0;
}

.upload-dialog-content {
    position: relative;
    min-height: 300px;
}

.upload-area {
    width: 100%;
}

.preview-area {
    margin-top: 24px;
    border-top: 1px solid #EBEEF5;
    padding-top: 20px;
}

.preview-area h4 {
    margin: 0 0 16px;
    color: #303133;
}

.file-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 16px;
}

.file-item {
    position: relative;
    border: 1px solid #EBEEF5;
    border-radius: 4px;
    overflow: hidden;
}

.preview-image {
    width: 100%;
    height: 150px;
    object-fit: cover;
}

.pdf-preview {
    height: 150px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 8px;
    background: #f5f7fa;
}

.pdf-preview .el-icon {
    font-size: 40px;
    color: #F56C6C;
}

.pdf-preview span {
    font-size: 12px;
    color: #606266;
    max-width: 90%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.delete-icon {
    position: absolute;
    top: 8px;
    right: 8px;
    padding: 4px;
    background: rgba(0, 0, 0, 0.5);
    border-radius: 50%;
    color: white;
    cursor: pointer;
    transition: all 0.3s;
}

.delete-icon:hover {
    background: rgba(0, 0, 0, 0.7);
    transform: scale(1.1);
}

:deep(.el-upload-dragger) {
    width: 100%;
}

:deep(.el-upload__tip) {
    margin-top: 8px;
    color: #909399;
}

.upload-section {
    border-right: 1px solid #EBEEF5;
}

:deep(.el-card__body) {
    height: 100%;
    padding: 0;
    background: linear-gradient(to bottom, rgba(255, 255, 255, 0.8), rgba(255, 255, 255, 1));
}

.type-container {
    padding: 20px;
}

.type-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 24px;
    padding: 20px 0;
}

.type-card {
    height: 100px;
    cursor: pointer;
    transition: all 0.3s;
}

.type-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.type-content {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.type-name {
    font-size: 18px;
    font-weight: 500;
    color: #303133;
}

.preview-button {
    position: absolute;
    top: 20px;
    right: 20px;
}

.items-form {
    padding: 0;
}

.items-form :deep(.el-form-item) {
    margin-bottom: 24px;
}

.items-form :deep(.el-form-item__label) {
    font-weight: 500;
    color: #606266;
}

.item-dialog-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 30px;
    border-top: 1px solid #EBEEF5;
}

.footer-left {
    flex: 1;
}

.footer-right {
    display: flex;
    gap: 12px;
}

.preview-content {
    padding: 20px;
}

.preview-section {
    margin-bottom: 24px;
}

.preview-section h3 {
    margin: 0 0 16px;
    padding-bottom: 8px;
    border-bottom: 1px solid #EBEEF5;
    color: #303133;
}

.preview-items {
    display: flex;
    flex-direction: column;
    gap: 16px;
    padding: 8px 0;
}

.preview-item {
    display: flex;
    align-items: center;
    gap: 16px;
}

.item-name {
    color: #606266;
    min-width: 120px;
    text-align: right;
}

.preview-input {
    flex: 1;
    max-width: 300px;
}

/* 折叠面板样式优 */
:deep(.el-collapse) {
    border: none;
}

:deep(.el-collapse-item__header) {
    font-size: 16px;
    font-weight: 500;
    color: #303133;
    background-color: #f5f7fa;
    padding: 12px 20px;
    border-radius: 4px;
}

:deep(.el-collapse-item__content) {
    padding: 20px;
}

:deep(.el-collapse-item__wrap) {
    border: none;
}

/* 输入框样式优化 */
.preview-input :deep(.el-input__wrapper) {
    border-radius: 4px;
}

.preview-input :deep(.el-input-group__append) {
    min-width: 50px;
    text-align: center;
    color: #606266;
    background-color: #f5f7fa;
    border-color: #dcdfe6;
}

/* hover效果 */
.preview-input :deep(.el-input__wrapper:hover) {
    box-shadow: 0 0 0 1px #409EFF;
}

/* 手动输入对话框样式 */
.manual-dialog :deep(.el-dialog) {
    min-height: 600px;
    display: flex;
    flex-direction: column;
}

.manual-dialog :deep(.el-dialog__body) {
    flex: 1;
    overflow-y: auto;
    padding: 30px;
}

.manual-dialog-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 30px;
    border-top: 1px solid #EBEEF5;
}

/* 项目输入对话框样式 */
.item-dialog :deep(.el-dialog) {
    min-height: 500px;
    display: flex;
    flex-direction: column;
}

.item-dialog :deep(.el-dialog__body) {
    flex: 1;
    overflow-y: auto;
    padding: 30px 20px;
}

.items-form {
    padding: 0;
}

.items-form :deep(.el-form-item) {
    margin-bottom: 24px;
    padding-right: 40px;
}

.items-form :deep(.el-form-item__label) {
    font-weight: 500;
    color: #606266;
}

.item-dialog-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 30px;
    border-top: 1px solid #EBEEF5;
}

.footer-left {
    flex: 1;
}

.footer-right {
    display: flex;
    gap: 12px;
}

/* 化输入框样式 */
.items-form :deep(.el-input-group__append) {
    min-width: 50px;
    text-align: center;
    color: #606266;
    background-color: #f5f7fa;
    border-color: #dcdfe6;
}

.items-form :deep(.el-form-item) {
    margin-bottom: 24px;
    padding-right: 40px;
}

.items-form :deep(.el-form-item__label) {
    font-weight: 500;
    color: #606266;
}

/* 输入框hover效果 */
.items-form :deep(.el-input__wrapper:hover) {
    box-shadow: 0 0 0 1px #409EFF;
}

/* 确保输入框和单位对齐 */
.items-form :deep(.el-input-group) {
    vertical-align: middle;
}

/* 调整对话框内容区域的样式 */
.item-dialog :deep(.el-dialog__body) {
    padding: 30px 20px;
}

.items-form {
    max-width: 600px;
    margin: 0 auto;
}

/* 预览对话框整体样式 */
.preview-dialog :deep(.el-dialog) {
    min-height: 80vh;
    display: flex;
    flex-direction: column;
    border-radius: 12px;
}

.preview-dialog :deep(.el-dialog__body) {
    flex: 1;
    overflow-y: auto;
    padding: 24px;
    background-color: #f5f7fa;
}

/* 折叠面板样式 */
:deep(.el-collapse) {
    border: none;
    background: transparent;
}

:deep(.el-collapse-item) {
    margin-bottom: 16px;
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
    transition: all 0.3s;
}

:deep(.el-collapse-item:hover) {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.collapse-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    padding: 8px 0;
}

.header-left {
    display: flex;
    align-items: center;
    gap: 12px;
}

.type-icon {
    font-size: 20px;
    color: #409EFF;
}

.type-title {
    font-size: 16px;
    font-weight: 500;
    color: #303133;
}

.header-right {
    width: 200px;
}

.completion-progress {
    margin-right: 16px;
}

/* 输入项样式 */
.preview-items {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
    padding: 16px;
}

.preview-item {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 16px;
    transition: all 0.3s;
}

.preview-item:hover {
    background: #eef2f6;
    transform: translateY(-2px);
}

.item-info {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;
}

.item-name {
    font-weight: 500;
    color: #303133;
}

.item-unit {
    color: #909399;
    font-size: 13px;
}

.preview-input :deep(.el-input__wrapper) {
    box-shadow: none;
    background: white;
}

.preview-input :deep(.el-input__wrapper:hover) {
    box-shadow: 0 0 0 1px #409EFF;
}

/* 底部式 */
.preview-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 24px;
    background: white;
    border-top: 1px solid #ebeef5;
}

.completion-info {
    display: flex;
    align-items: center;
    gap: 16px;
}

.total-progress {
    width: 200px;
}

/* 报告对话框样式 */
.report-dialog :deep(.el-dialog) {
    min-height: 50vh;
    max-height: 80vh;
    display: flex;
    flex-direction: column;
}

.report-dialog :deep(.el-dialog__body) {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;
    background: #f5f7fa;
    overflow: auto;
}

/* 生成中的动画样式 */
.generating-content {
    text-align: center;
    padding: 30px;
}

.generating-animation {
    font-size: 40px;
    color: #409EFF;
    margin-bottom: 16px;
}

.rotating {
    animation: rotate 1.5s linear infinite;
}

.generating-content h3 {
    color: #303133;
    margin: 0 0 12px;
}

.generating-tip {
    color: #909399;
    margin: 0;
}

/* 报告预览样式 */
.report-preview {
    width: 100%;
    height: 100%;
    overflow: auto;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 10px;
}

.report-image {
    max-width: 95%;
    height: auto;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    transition: transform 0.3s ease;
}

.report-image:hover {
    transform: scale(1.02);
}

.report-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    border-top: 1px solid #ebeef5;
}

.action-buttons {
    display: flex;
    gap: 12px;
}

@keyframes rotate {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}

/* Element Plus v-loading 自定义样式 */

/* 优化对话框样式 */
.template-dialog :deep(.el-dialog) {
    max-height: 90vh;
}

.template-preview {
    padding: 10px;
}

.template-image {
    max-height: 70vh;
    object-fit: contain;
}

.template-hint {
    text-align: center;
    margin-bottom: 20px;
}

.template-btn {
    font-size: 14px;
    color: #E6A23C;
    transition: all 0.3s;
    padding: 8px 16px;
    border-radius: 4px;
}

.template-btn:hover {
    color: #F56C6C;
    transform: translateY(-2px);
    background: rgba(230, 162, 60, 0.1);
}

.upload-dialog-content {
    padding: 20px 0;
}

/* 记录查看对话框样式 */
.records-dialog :deep(.el-dialog) {
    max-height: 80vh;
}

.records-dialog :deep(.el-dialog__body) {
    padding: 0;
    height: 500px;
    overflow: hidden;
}

.records-dialog :deep(.el-table) {
    height: 100%;
}

.records-dialog :deep(.el-table__body-wrapper) {
    overflow-y: auto;
}

.records-dialog :deep(.el-table__header-wrapper) {
    position: sticky;
    top: 0;
    z-index: 1;
    background-color: #fff;
}

.view-records-btn {
    position: fixed;
    bottom: 30px;
    right: 30px;
    z-index: 100;
    border-radius: 8px;
    padding: 10px 20px;
    display: flex;
    align-items: center;
    gap: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 记录对话框样式 */
.records-dialog {
    border-radius: 8px;
    overflow: hidden;
}

:deep(.el-dialog__header) {
    margin: 0;
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;
}

:deep(.el-dialog__body) {
    padding: 20px;
}

/* 表格样式优化 */
:deep(.el-table) {
    --el-table-border-color: #f0f0f0;
    --el-table-header-bg-color: #f5f7fa;
}

:deep(.el-table th) {
    font-weight: 600;
    color: #606266;
}

:deep(.el-table__row) {
    transition: all 0.3s;
}

:deep(.el-table__row:hover) {
    background-color: #f5f7fa;
}

/* 文件路径链接样式 */
.file-path-link {
    color: #409EFF;
    text-decoration: none;
    transition: all 0.3s;
}

.file-path-link:hover {
    color: #66b1ff;
    text-decoration: underline;
}
</style>
